package com.siemens.industrial.web.mvc.service.partner;

import com.siemens.industrial.model.partner.User;
import com.siemens.industrial.utils.GlobalResponseCode;
import com.siemens.industrial.utils.SiemensException;
import com.siemens.industrial.web.mvc.dao.partner.PartnerUserDao;
import com.siemens.industrial.web.mvc.pojo.DataTableQuery;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by qupen on 2016/8/31.
 */
@Service
public class PartnerUserService {
    @Resource
    PartnerUserDao partnerUserDao;

    @Resource
    JdbcTemplate jdbcTemplate;

    public User getUser(String tenantKey, String tenantId, String userId) {
        return partnerUserDao.getUser(tenantKey, tenantId, userId);
    }

    public List<User> getUsers(String tenantKey, String tenantId) {
        return partnerUserDao.getUsers(tenantKey, tenantId);
    }

    @Transactional
    public int saveUser(String tenantKey, String tenantId, User user) throws SiemensException {
        if (partnerUserDao.getUserByName(tenantKey, tenantId, user.getUserName()) == null) {
            return partnerUserDao.saveUser(tenantId, user);
        } else {
            throw new SiemensException(GlobalResponseCode.ERROR_USER_EXISTED);
        }
    }

    @Transactional
    public String updateUser(String tenantKey, String tenantId, Map<String, String> data) throws SiemensException {
        if (data.containsKey("userId")) {
            User user = partnerUserDao.getUser(tenantKey, tenantId, data.get("userId"));
            this.buildUserForCreate(data,user);
            partnerUserDao.updateUser(tenantId,user);
            return user.getUserId();
        } else {
            throw new SiemensException(GlobalResponseCode.ERROR_USER_NOT_EXISTED);
        }
    }

    @Transactional
    public int updateUserPwd(String tenantKey,String tenantId, String userId, String password) throws SiemensException {
        if (partnerUserDao.getUser(tenantKey, tenantId, userId) != null) {
           return partnerUserDao.updateUserPwd(tenantId, userId, password);
        } else {
            throw new SiemensException(GlobalResponseCode.ERROR_USER_NOT_EXISTED);
        }
    }

    @Transactional
    public void deleteUser(String tenantKey, String tenantId, String userId) throws SiemensException {
        if (partnerUserDao.getUser(tenantKey, tenantId, userId) != null) {
            partnerUserDao.deleteUser(tenantId, userId);
        } else {
            throw new SiemensException(GlobalResponseCode.ERROR_USER_NOT_EXISTED);
        }
    }

    @Transactional
    public void recoveryUser(String tenantKey, String tenantId, String userId) throws SiemensException {
        if (partnerUserDao.getDisabledUser(tenantKey, tenantId, userId) != null) {
            partnerUserDao.recoveryUser(tenantId, userId);
        } else {
            throw new SiemensException(GlobalResponseCode.ERROR_USER_NOT_EXISTED);
        }
    }

    public void setTenantUserEnabled(String tenantId, int enabled, String tenantUserId) {
        partnerUserDao.updateTenantUserEnabled(tenantId, enabled, tenantUserId);
    }

    /**
     * userId and password need put in controller
     *
     * @param data
     * @param user
     * @return
     */
    public User buildUserForCreate(Map<String, String> data, User user) {
        if (data.containsKey("userName")) {
            user.setUserName(data.get("userName"));
        }
        if (data.containsKey("telephone")) {
            user.setTelephone(data.get("telephone"));
        }
        if (data.containsKey("mail")) {
            user.setEmail(data.get("mail"));
        }
        if (data.containsKey("department")) {
            user.setDepartment(data.get("department"));
        }
        if (data.containsKey("job")) {
            user.setJob(data.get("job"));
        }
        if (data.containsKey("group")) {
            user.setGroup(data.get("group"));
        }
        if (data.containsKey("logoMd5")) {
            user.setLogoMd5(data.get("logoMd5"));
        }
        if (data.containsKey("role")){
            user.setRoleId(Integer.parseInt(data.get("role")));
        }
        return user;
    }

    public List<Map<String, Object>> getUserGroupName(String tenantId) {
        return partnerUserDao.getUserGroup(tenantId);
    }

    public List<Map<String,Object>> getTenantServiceByTenantId(String tenantId){
        return partnerUserDao.getTenantService(tenantId);
    }

    //dataTable search users
    public Map<String, Object> getUsersByDataTable(String tenantKey, String tenantId, HttpServletRequest request) {
        DataTableQuery dt = new DataTableQuery(request);
        List<Map<String,Object>> list = new ArrayList<>();

        String sql = "SELECT '"+ tenantKey +"' tenant_key,user_id,user_name, user_pwd, role_id, enabled, contact, telephone, email, department, job, `group`, logo_md5, dashboard_config, create_time, update_time \n" +
                "FROM `"+ tenantId +"`.`user` WHERE 1=1 ";
        int total = jdbcTemplate.queryForList(sql).size();

        int filteredCount = total;
        if (!dt.getSearch().equals("")){
            String search = " and (user_name like binary '%"+ dt.getSearch() +"%' or telephone like binary '%"+ dt.getSearch() +"%' or department like binary '%"+ dt.getSearch() +"%')";
            sql += search;
            filteredCount = jdbcTemplate.queryForList(sql).size();
        }

        if (!dt.getOrderDBColumn().equals("") && !dt.getOrderAscOrDesc().equals("")){
            String order = " order by `"+ dt.getOrderDBColumn() + "`" + dt.getOrderAscOrDesc();
            sql += order;
        }

        String limit = " limit " +dt.getStart() + "," + dt.getLength();
        sql += limit;

        list = jdbcTemplate.queryForList(sql);

        return dt.buildResponse(filteredCount,total,list);
    }

    //dataTable search tenant service
    public Map<String,Object> getTenantServiceByIdAndDataTable(String tenantId,HttpServletRequest request){
        DataTableQuery dt = new DataTableQuery(request);
        List<Map<String,Object>> list = new ArrayList<>();

        String sql = "SELECT * FROM (\n" +
                "SELECT \n" +
                "    a.service_name,\n" +
                "    a.service_desc,\n" +
                "    c.enabled,\n" +
                "    c.start_date,\n" +
                "    c.end_date," +
                "    CONCAT(c.start_date, ' - ', c.end_date) `date`\n" +
                "FROM\n" +
                "    siemens.service a\n" +
                "        LEFT JOIN\n" +
                "    (SELECT \n" +
                "        *\n" +
                "    FROM\n" +
                "        siemens.tenant_service_relation b\n" +
                "    WHERE\n" +
                "        b.tenant_id = '"+ tenantId +"') c ON a.service_id = c.service_id) dt\n" +
                "WHERE 1=1\n";
        int total = jdbcTemplate.queryForList(sql).size();
        int filteredCount = total;
        if(!dt.getSearch().equals("")){
            String search = " and (dt.service_name like binary '%"+ dt.getSearch() +"%' or dt.service_desc like binary '%"+ dt.getSearch() +"%' or dt.start_date like binary '%"+ dt.getSearch() +"%' or dt.end_date like binary '%"+ dt.getSearch() +"%')";
            sql += search;
            filteredCount = jdbcTemplate.queryForList(sql).size();
        }

        if(!dt.getOrderDBColumn().equals("") && !dt.getOrderAscOrDesc().equals("")){
            String order = " order by `" + dt.getOrderDBColumn() + "` "+ dt.getOrderAscOrDesc();
            sql += order;
        }

        String limit = " limit " + dt.getStart() + "," +dt.getLength();
        sql += limit;

        list = jdbcTemplate.queryForList(sql);
        return dt.buildResponse(filteredCount,total,list);
    }
}
